const getLocalStorage = (key) => {
  const value = localStorage.getItem(key)
  if (value === null) {
    return null
  }
  try {
    return JSON.parse(value)
  } catch (error) {
    return value
  }
}
const setLocalStorage = (key, value) => {
  localStorage.setItem(key, JSON.stringify(value))
}

/**
 * @description 递归查询对应的路由
 * @param {String} path 当前访问地址
 * @param {Array} routes 路由列表
 * @returns array
 */
const searchRoute = (path, routes) => {
  let result = {}
  for (let item of routes) {
    if (item.path === path) return item
    if (item.children) {
      const res = searchRoute(path, item.children)
      if (Object.keys(res).length) result = res
    }
  }
  return result
}

/**
 * @description 递归处理路由菜单，生成一维数组，做菜单权限判断
 * @param {Array} menuList 所有菜单列表
 * @returns array
 */
const handleRouter = (menuList) => {
  let newArr = []
  menuList.forEach((item) => {
    if (item.children && item.children.length > 0) {
      newArr.push(...handleRouter(item.children))
    } else {
      newArr.push(item.path)
    }
  })
  return newArr
}
/**
 * @description 获取需要展开的 subMenu
 * @param {String} path 当前访问地址
 * @returns array
 */
const getOpenKeys = (path) => {
  let newStr = ''
  let newArr = []
  let arr = path.split('/').map((i) => '/' + i)
  for (let i = 1; i < arr.length - 1; i++) {
    newStr += arr[i]
    newArr.push(newStr)
  }
  return newArr
}

/**
 * @description 获取浏览器默认语言
 * @return string
 */
const getBrowserLang = () => {
	let browserLang = navigator.language ? navigator.language : navigator.browserLanguage;
	let defaultBrowserLang = "";
	if (browserLang.toLowerCase() === "cn" || browserLang.toLowerCase() === "zh" || browserLang.toLowerCase() === "zh-cn") {
		defaultBrowserLang = "zh";
	} else {
		defaultBrowserLang = "en";
	}
	return defaultBrowserLang;
}; 

export {
  getLocalStorage,
  setLocalStorage,
  searchRoute,
  handleRouter,
  getOpenKeys,
  getBrowserLang
}
